<?php

namespace app\yperp\logic\yp;

use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;

class JstOrder
{
    const EXPR_COMPR = [
        '极兔',
        '京广',
        '民生',
        '顺心捷达',
        '京东',
        '安能物',
        '虚拟发货',
        '顺丰',
        'sec11',
        '百世',
        '中通',
        '申通',
        '圆通',
        '韵达',
        '邮政',
        'EMS',
        '天天',
        '优速',
        '德邦',
        '宅急送',
    ];
    private static $instance;
    protected $token;
    public static function getInstance()
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    /**
     * 虹创登录密码加解密
     * @param string $string
     * @param string $key
     * @return string
     */
    function getExprCodeOne($ypOrderCoce = [])
    {
        if (is_string($ypOrderCoce)) {
            $ypOrderCoce = [$ypOrderCoce];
        }
        $body = [
            'soIdList' => $ypOrderCoce,
            "orderTypeEnum" => "ALL",
            "ascOrDesc" => false,
            "pageNum" => 1,
            "pageSize" => 500
        ];

        $response = $this->request($body);

        if ($response['success'] && $response['total'] > 0) {
            $res = $response['data'][0];
            foreach (JstOrder::EXPR_COMPR as $value) {
                //判断字符串是否在一个字符串中 
                if (strpos($res['expressCompany'], $value) !== false) {
                    $res['expressCompany'] = $value;
                }
            }
            return $res;
        } else {
            dump($response);
            dump($ypOrderCoce);
            dump('聚水潭未获取到物流信息!');
            return [];
        }
    }


    protected function request(array $body = [])
    {
        $client = new Client([
            'verify' => env('root_path') . 'application\yperp\common\cacert.pem',
            // 忽略证书验证
        ]);

        $jst_token = module_config('yperp.jst_token');
        $headers = [
            'authorization' => $jst_token,
            'content-type' => 'application/json;charset=UTF-8'
        ];
        // $body = '{"soIdList":["HC2404125561000582"],"orderTypeEnum":"ALL","ascOrDesc":false,"pageNum":1,"pageSize":500}';
        // $body = [
        //     'soIdList' => $ypOrderCoce,
        //     "orderTypeEnum" => "ALL",
        //     "ascOrDesc" => false,
        //     "pageNum" => 1,
        //     "pageSize" => 500
        // ];
        $request = new Request('POST', 'https://innerapi.scm121.com/api/inner/order/list', $headers, json_encode($body, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
        $res = $client->sendAsync($request)->wait();
        $data = $res->getBody()->getContents();
        return json_decode($data, true);
    }
}
